'use strict';

const Service = require('egg').Service;

class BaseService extends Service {

  constructor(primary_model, ...props) {
    super(...props)
    this.primary_model = this.ctx.model[primary_model]
  }
  
  //查找
  async find(id, findWhere = {}){
    const {primary_model} = this
    const args = arguments
    if(arguments.length <= 1) {
      return await primary_model.findByPk(id)
    }else {
      const { where = {} } = findWhere
      return await primary_model.findOne({
        ...findWhere, where: {id, ...where}
      })
    }
  }

  //查找并创建
  async findOrCreate(defaults, whereArr){
    const {primary_model} = this;
    const where = {}
    if(typeof whereArr === 'string') {
      const value = whereArr
      where[value] = defaults[value]
    }else if(Array.isArray(whereArr)) {
      for(let value of  whereArr) {
        where[value] = defaults[value]
      }
    }
    const [record, created] = await primary_model.findOrCreate({where,defaults})
    return {record, created}
  }

  //查找全部可用
  async findAll(findWhere = {}) {
    const {primary_model} = this;
    return await primary_model.findAll({
      where: {status: "1"},
      ...findWhere
    });
  }

  //创建添加
  async create(newRecord) {
    const {primary_model} = this;
    return await primary_model.create(newRecord);
  }

  //更新
  async update(id, newRecord) {
    const {primary_model} = this;
    const user = await primary_model.findByPk(id);
    for(let pro in newRecord) {
      //自动过滤
      if(pro in user) user[pro] = newRecord[pro];
    }
    return await user.save();
  }

  //删除记录
  async softDestroy(id,){
    const {primary_model} = this;
    const record = await primary_model.findByPk(id);
    record.status = "0";
    return await record.save();
  }

  //恢复记录
  async softRecover(id){
    const {primary_model} = this;
    const record = await primary_model.findByPk(id);
    record.status = "1";
    return await record.save();
  }
}

module.exports = BaseService;
